package com.yungu.swift.socket.push.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.socket.component.ChannelKeeper;
import com.yungu.swift.socket.push.model.PushContent;
import com.yungu.swift.socket.push.service.PushService;
import com.yungu.swift.socket.push.task.AdminPushTask;
import com.yungu.swift.socket.push.task.SimplePushTask;
import com.yungu.swift.utils.JsonUtils;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.*;


/**
 * PushServiceImpl
 *
 * @author cuixiuyin
 * @date 2018/12/15
 */
@Service(interfaceName = "com.yungu.swift.socket.push.service.PushService", loadbalance = "socketClusterLoadBalance")
public class PushServiceImpl implements PushService {

    private static final Logger logger = LoggerFactory.getLogger(PushServiceImpl.class);

    /**
     * 线程池大小
     */
    private static final int POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;

    private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("push-pool-%d").build();
    /**
     * 推送线程池
     */
    private static ExecutorService POOL = new ThreadPoolExecutor(POOL_SIZE, 200, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), namedThreadFactory,
            new ThreadPoolExecutor.AbortPolicy());

    @Override
    public void sendMessage(String targetUuid, PushContent pushContent) {
        logger.info("推送消息-对象[{}]-数据[{}]", targetUuid, JsonUtils.toJSONString(pushContent));
        POOL.execute(new SimplePushTask(Lists.newArrayList(targetUuid), pushContent, null));
    }

    @Override
    public void sendMessageByList(List<String> targetUuids, PushContent pushContent) {
        logger.info("批量推送消息，对象数量【{}】,【{}】,数据【{}】", targetUuids.size(), targetUuids, JsonUtils.toJSONString(pushContent));
        POOL.execute(new SimplePushTask(targetUuids, pushContent, null));
    }

    @Override
    public void sendMessageByAdmin(PushContent pushContent) {
        logger.info("批量推送消息 >> 后台登录用户， 内容【{}】", JsonUtils.toJSONString(pushContent));
        POOL.execute(new AdminPushTask(pushContent));
    }

    /**
     * 通过id判断通道是否存在
     */
    @Override
    public ResponseData<Boolean> getChannel(String targetUuid) {
        Channel channel = ChannelKeeper.get(targetUuid);
        if (channel != null) {
            logger.info("---{}主动查询通道成功---", targetUuid);
            return ResponseData.buildSuccessResponse("获取通道成功", true);
        }
        logger.info("---{}主动查询通道失败---", targetUuid);
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "通道不存在", false);
    }
}
